package cn.wolfcode.p2p.base.service.impl;

import cn.wolfcode.p2p.base.domain.LoginInfo;
import cn.wolfcode.p2p.base.domain.UserInfo;
import cn.wolfcode.p2p.base.exception.CustomerException;
import cn.wolfcode.p2p.base.mapper.UserInfoMapper;
import cn.wolfcode.p2p.base.service.IUserInfoService;
import cn.wolfcode.p2p.util.BitStatesUtil;
import cn.wolfcode.p2p.util.UserContext;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

@Service
@Transactional
public class UserInfoServiceImpl implements IUserInfoService {
    @Autowired
    private UserInfoMapper userInfoMapper;

    @Override
    public void init(LoginInfo loginInfo) {
        UserInfo userInfo = new UserInfo();
        userInfo.setPhoneNumber(loginInfo.getUsername());
        userInfo.setId(loginInfo.getId());
        userInfoMapper.insert(userInfo);
    }

    @Override
    public UserInfo getById(Long id) {
        return userInfoMapper.selectByPrimaryKey(id);
    }

    @Override
    public void basicInfo_save(UserInfo userInfo) {
        LoginInfo currentUser = UserContext.getCurrentUser();
        //根据用户id查出用户个人信息
        UserInfo oriUser = userInfoMapper.selectByPrimaryKey(currentUser.getId());
        oriUser.setBitState(0L);
        oriUser.setEducationBackground(userInfo.getEducationBackground());
        oriUser.setMarriage(userInfo.getMarriage());
        oriUser.setKidCount(userInfo.getKidCount());
        oriUser.setHouseCondition(userInfo.getHouseCondition());
        oriUser.setIncomeGrade(userInfo.getIncomeGrade());

        //添加位状态
        if (!oriUser.hasBasicInfo()) {
            Long tempState = BitStatesUtil.addState(oriUser.getBitState(), BitStatesUtil.OP_BASIC_INFO);
            oriUser.setBitState(tempState);
        }
        update(oriUser);
    }

    public void update(UserInfo userInfo) {
        int i = userInfoMapper.updateByPrimaryKey(userInfo);
        if (i == 0) {
            //没有更新成功
            throw new CustomerException("用户信息修改失败,请稍后再试:乐观锁异常[" + userInfo.getId() + "]");
        }
    }
}
